<template>
  <view class="city-indexes">
    <scroll-view
      v-if="list.length"
      :scroll-y="true"
      :scroll-top="scrollTop"
      :enable-back-to-top="true"
      :scroll-with-animation="true"
      class="city-indexes-content"
      :scroll-into-view="scrollIntoViewId"
      @scroll="handleScroll"
    >
      <view
        v-for="item in list"
        :id="item.key"
        :key="item.key"
        class="content-item"
      >
        <view class="content-wrap" @tap="handleChange">
          <view class="content-wrap-title">
            {{ item.key }}
          </view>
          <view class="content-list">
            <view
              v-for="lc in item.items"
              :key="lc.id"
              :data-id="lc"
              class="content-list-item"
              :class="activeCityItemClass(lc.id)"
            >
              <view :data-id="lc">{{ lc.title }}</view>
              <image
                v-if="isShowActiveIcon(lc.id)"
                :data-id="lc"
                :lazy-load="true"
                class="active-icon"
                :src="SELECT_CITY_ICON"
              />
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="city-indexes-key" @tap="handleScrollIndex">
      <view
        v-for="keys in list"
        :key="keys.key"
        :class="`key-item ${getActiveKey(keys.key)}`"
        :data-key="keys.key"
      >
        {{ keys.key }}
      </view>
    </view>
  </view>
</template>

<script>
import Taro, { nextTick } from "@tarojs/taro";
import { IMAGE_CDN } from "@/config/index.ts";
const SELECT_CITY_ICON = `${ IMAGE_CDN }/SELECT_CITY_ICON.png`
import "./index.scss";
export default {
  props: {
    cityInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    /**索引数据 */
    list: {
      type: Array,
      default: () => []
    },
    /**是否显示勾选小图标 */
    isShowSelectIcon: {
      type: Boolean,
      default: false
    },
    /**是否重新计算 */
    isStartCountScrollTop: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      SELECT_CITY_ICON,
      scrollTop: 0,
      scrollIntoViewId: "A",
      activeKey: "A",
      oHeight: [],
      midScrollTop: 0
    };
  },
  computed: {
    /**右侧索引数据 */
    indexSource() {
      return this.list.map(i => i.key);
    }
  },
  watch: {
    list(newValue) {
      if (newValue.length) {
        Taro.nextTick(() => {
          if (!this.list.length) return;
          if (this.isStartCountScrollTop) {
            this.scrollTop = 0;
          }
          this.getBrands();
          const firstChild = this.list[0];
          this.activeKey = firstChild.key;
        });
      }
    }
    // isStartCountScrollTop(newVal) {
    //   if (newVal) {
    //     this.scrollTop = 0;
    //     this.$emit("update:isStartCountScrollTop", false);
    //   }
    // }
  },
  created() {
    this.handleInitData();
  },
  mounted() {
    this.scrollTop = 0;
    Taro.nextTick(() => {
      this.getBrands();
    });
  },
  methods: {
    handleInitData() {
      if (!this.list.length) return;
      const firstChild = this.list[0];
      this.scrollIntoViewId = this.activeKey = firstChild.key;
    },
    /**是否显示已选icon */
    isShowActiveIcon(id) {
      return this.cityInfo.id === id && this.isShowSelectIcon;
    },
    activeCityItemClass(id) {
      return {
        "active-city": this.cityInfo.id === id && !this.isShowSelectIcon
      };
    },
    handleChange({ target: { dataset } }) {
      const { id: selectCityInfo } = dataset;
      if (!selectCityInfo) return;
      /**点击本身 */
      if (this.cityInfo.id === selectCityInfo.id) {
        this.$emit("changeOwn");
        return;
      }
      this.isOpened = true;
      this.currentCity = selectCityInfo;
      this.$emit("changeCity", selectCityInfo);
    },
    /**处理已滑到某个区域 */
    handleScroll({ detail }) {
      let scrollTop = detail.scrollTop;
      this.midScrollTop = scrollTop;
      /**防止点击字母定位时超过最大scorllTop值，而再次出现滚动 */
      if (this.scrollTop > scrollTop) return;
      for (let i = 0; i < this.oHeight.length; i++) {
        if (scrollTop >= 0 && scrollTop + 10 < this.oHeight[0].height) {
          this.activeKey = this.oHeight[0].key;
        } else if (scrollTop + 10 <= this.oHeight[i].height) {
          this.activeKey = this.oHeight[i].key;
          return;
        }
      }
    },
    /**初始化获取各个模块的高度 */
    getBrands() {
      let scrollTop = 0;
      this.scrollTop += 0.01;
      this.oHeight = [];
      for (let i = 0; i < this.list.length; i++) {
        Taro.createSelectorQuery()
          .select(`#${this.list[i].key}`)
          .fields(
            {
              dataset: true,
              size: true,
              scrollOffset: true,
              properties: ["scrollX", "scrollY"]
            },
            ({ height }) => {
              scrollTop += height;
              this.oHeight.push({
                height: scrollTop,
                key: this.list[i].key,
                ownHeight: height
              });
            }
          )
          .exec();
      }
      this.$emit("update:isStartCountScrollTop", false);
    },
    getActiveKey(key) {
      return this.activeKey === key ? "actived" : "";
    },
    handleScrollIndex({ target: { dataset } }) {
      const { key } = dataset;
      this.activeKey = key;
      let top = 0;
      const source = this.oHeight.find(i => i.key === key);
      const sourceIndex = this.oHeight.findIndex(i => i === source);
      if (sourceIndex === 0) {
        this.scrollTop = top + 0.01;
      } else {
        this.scrollTop = source.height - source.ownHeight;
      }
    }
  }
};
</script>
